package jmind.core.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

public abstract class TJdbc extends BaseJdbc {

	public abstract <T> T parse(ResultSet rs) throws SQLException;

	public <T> T findOne(int source, String sql, Object... args) {
		ResultSetExtractor<T> res = new ResultSetExtractor<T>() {
			@Override
			public T extractData(ResultSet rs) throws SQLException, DataAccessException {
				if (rs.next()) {
					return parse(rs);
				}
				return null;
			}
		};

		return getJdbc(source).query(sql, res, args);
	}

	public <T> List<T> find(int source, String sql, Object... args) {
		List<T> list = getJdbc(source).query(sql, new RowMapper<T>() {
			public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
				return parse(rs);
			}
		}, args);
		return list;
	}

}
